package rightsmanagement;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import superkigav.shared.rightsmanagement.ApplicationFunction;
import superkigav.shared.rightsmanagement.IRights;
import superkigav.shared.rightsmanagement.UserGroup;
import superkigav.shared.rightsmanagement.UserTicket;

public class RightsService implements IRights {
	private ArrayList<PairAppfunctionGroup> rightsCache;
	private RightsAdministrationService rightsAdministrationService;
	private static BufferedReader inStream;
	final private static String permissionsPath = System
			.getProperty("user.dir") + "\\Permissions.txt";

	public RightsService() {
		this.rightsCache = new ArrayList<PairAppfunctionGroup>();
		this.rightsAdministrationService = RightsAdministrationService
				.getRightsAdministrationService();
	}

	@Override
	public UserTicket authenticate(String user, String password) {
		return this.rightsAdministrationService.authenticate(user, password);
	}

	@Override
	public boolean isAccessPermitted(UserTicket user,
			ApplicationFunction function) {
		try {
			updateRightsCache();
			PairAppfunctionGroup requestPair = new PairAppfunctionGroup(
					function, user.getUserGroup());
			for (PairAppfunctionGroup pag : rightsCache) {
				if (pag.equals(requestPair)) {
					return true;
				}
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	private void initStreams() throws FileNotFoundException {
		inStream = new BufferedReader(new FileReader(permissionsPath));
	}

	private void updateRightsCache() throws IOException, FileNotFoundException {
		initStreams();
		String line;
		while ((line = inStream.readLine()) != null) {
			String[] parts = line.split(";");
			if (parts.length != 2)
				throw new RuntimeException();
			try {
				rightsCache.add(new PairAppfunctionGroup(
						new ApplicationFunction(parts[0]), new UserGroup(
								new Integer(parts[1]))));
			} catch (Throwable t) {
				t.printStackTrace();
			}
		}
	}

}
